package com.yang.frost.blueberry.weixin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yang.frost.blueberry.config.properties.WxProperties;
import com.yang.frost.blueberry.domain.WxAccessToken;
import com.yang.frost.blueberry.util.HttpRequestUtil;
import com.yang.frost.blueberry.util.OkHttpUtil;
import com.yang.frost.blueberry.weixin.config.WxConfig;
import com.yang.frost.blueberry.weixin.exception.WxErrorException;
import com.yang.frost.blueberry.weixin.service.WxService;
import com.yang.frost.blueberry.weixin.util.WeChatUtil;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 10296
 * @date 2021/1/29
 * @Description:
 */
@Service
public class WxServiceImpl implements WxService {

    private Logger logger = LoggerFactory.getLogger(WxService.class);

    private static WxAccessToken wxAccessToken;
    @Autowired
    private WxProperties wxProperties;

    @Autowired
    private HttpRequestUtil requestUtil;

    @Override
    public boolean checkSignature(String timestamp, String nonce, String signature) {
        return WeChatUtil.checkSignature(timestamp, nonce, signature);
    }

    @Override
    public String getAccessToken() throws WxErrorException {


        if (wxAccessToken != null && !wxAccessToken.isExpired()) {
            return wxAccessToken.getAccessToken();
        } else {
            JSONObject resData = getToken();
            String errcode = MapUtils.getString(resData, "errcode");
//            boolean b = StringUtils.isNotBlank(errcode) && (("42001").equals(errcode) || ("40001").equals(errcode) || ("40014").equals(errcode));
//
//            if (b) {
//                resData = getToken();
//
//            }
            String accessToken = MapUtils.getString(resData, "access_token");
            int expiresIn = MapUtils.getIntValue(resData, "expires_in");
            wxAccessToken = new WxAccessToken(accessToken, expiresIn);

        }
        return wxAccessToken.getAccessToken();

    }

    /**
     * 网络请求获取微信token
     *
     * @return ''
     */
    private JSONObject getToken() {
        String url = String.format(WxConfig.ACCESS_TOKEN, wxProperties.getAppId(), wxProperties.getAppSecret());
        return requestUtil.httpsRequest(url, "GET", null);
    }

    @Override
    public String getAccessToken(boolean forceRefresh) throws WxErrorException {

        return null;
    }


}
